<template>
  <div class="content pb_20">
    <!-- 搜索框、logo -->
    <Search />
    <div class="fontsize-22 seckill-title">限时秒杀</div>
    <!-- 秒杀时间段 -->
    <div class="time-line">
      <template v-for="(time, index) in list">
        <div v-if="index < 5" @click="currentChange(index)" :key="index" :class="{ currTimeline: currIndex === index }">
          <div class="mr_10">{{ time.timeLine + ":00" }}</div>
          <div v-if="currIndex === index" style="line-height: 22px;">
            <div>{{ nowHour >= time.timeLine ? "秒杀中" : "即将开始" }}</div>
            <div>{{ nowHour >= time.timeLine ? "距结束" : "距开始" }}&nbsp;{{currTime}}</div>
          </div>
          <div v-else class="not-curr">{{ nowHour >= time.timeLine ? "秒杀中" : "即将开始" }}</div>
        </div>
      </template>
    </div>
    <!-- 秒杀商品列表 -->
    <div class="goods-list">
      <div v-if="goodsList && goodsList.length" class="goods-show-info" v-for="(item, index) in goodsList" :key="index" @click="goGoodsDetail(item.skuId, item.goodsId)">
        <div class="goods-show-img"><img width="200" height="200" :src="item.goodsImage" /></div>
        <div class="goods-show-price">
          <span>
            <span class="seckill-price text-danger">{{unitPrice(item.price, "￥")}}</span>
            <span style="color: #999; text-decoration: line-through;font-size: 14px;">{{unitPrice(item.originalPrice, "￥")}}</span>
          </span>
        </div>
        <div class="goods-show-detail ellipsis ellipsis-2" style="margin-bottom: 20px"><span>{{ item.goodsName }}</span></div>
        <div class="goods-seckill-btn" :class="{ 'goods-seckill-btn-gray': nowHour < list[currIndex].timeLine,}">{{ nowHour >= list[currIndex].timeLine ? "立即抢购" : "即将开始" }}</div>
        <div v-if="nowHour >= list[currIndex].timeLine && item.quantity <= item.salesNum" class="goods-seckill-btn goods-seckill-btn-gray">已售罄</div>
        <div class="goods-show-num1">
          <div v-if="nowHour >= list[currIndex].timeLine">
            <span class="mr_10">已售{{(item.quantity && item.quantity > 0? (parseFloat((item.salesNum/item.quantity*100).toFixed(2))) :100) + "%"}}</span>
            <a-progress :percent="item.quantity && item.quantity > 0? (parseFloat((item.salesNum/item.quantity).toFixed(2))):1" :style="{width: '70px'}" :show-text="false" :status="item.quantity?'success':'danger'"></a-progress>
          </div>
        </div>
        <div class="goods-show-seller"><span>{{ item.storeName }}</span></div>
      </div>
      <Empty v-else />
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, watch } from 'vue';
  import { useRouter } from 'vue-router';
  import { unitPrice } from '@/utils/filters';
  import { seckillByDay } from "@/api/promotion";

  const router = useRouter();
  const list = ref<Array<any>>([]); // 秒杀时段列表
  const goodsList = ref<Array<any>>([]); // 商品列表
  const interval = ref<any>(null); // 定时器
  const currIndex = ref(0); // 当前时间段的下标
  const currTime = ref<any>(0); // 当前显示的倒计时
  const diffSeconds = ref(0); // 倒计时时间戳
  const nowHour = ref(new Date().getHours()); // 当前小时数


  const getListByDay = () => {
    // 当天秒杀活动
    seckillByDay().then((res) => {
      if (res.data.success) {
        list.value = res.data.result;
        goodsList.value = list.value[0].seckillGoodsList;
        countDown(currIndex.value);
      }
    });
  };
  // 倒计时 0点时间戳
  const countDown = (currIndex: any) => {
    let zeroTime = new Date(new Date().toLocaleDateString()).getTime();
    let currTime = new Date().getTime();
    let actTime = 0;
    let nowHour = new Date().getHours(); // 当前小时数
    if (list.value[currIndex].timeLine > nowHour) {
      // 活动未开始
      actTime = zeroTime + list.value[currIndex].timeLine * 3600 * 1000;
    } else if (list.value[currIndex].timeLine <= nowHour) {
      // 活动进行中
      if (currIndex === list.value.length - 1) {
        // 如果是最后一个活动，直到24点结束
        actTime = zeroTime + 24 * 3600 * 1000;
      } else {
        actTime = zeroTime + list.value[currIndex + 1].timeLine * 3600 * 1000;
      }
    }
    diffSeconds.value = Math.floor((actTime - currTime) / 1000);
    interval.value = setInterval(() => {
      diffSeconds.value--;
    }, 1000);
  };
  // 跳转商品详情
  const goGoodsDetail = (skuId: any, goodsId: any) => {
    let routeUrl = router.resolve({path: "/goodsDetail", query: { skuId, goodsId },});
    window.open(routeUrl.href, "_blank");
  };
  // 切换秒杀时间段
  const currentChange = (index: any) => {
    currIndex.value = index;
    clearInterval(interval.value);
    interval.value = null;
    nowHour.value = new Date().getHours();
    countDown(currIndex.value);
    goodsList.value = list.value[currIndex.value].seckillGoodsList;
  };
  watch(()=>diffSeconds.value, (val) => {
    const hours = Math.floor(val / 3600);
    // 当前秒数 / 60，向下取整
    // 获取到所有分钟数 3600 / 60 = 60分钟
    // 对60取模，超过小时数的分钟数
    const minutes = Math.floor(val / 60) % 60;
    // 当前的秒数 % 60，获取到 超过小时数、分钟数的秒数（秒数）
    const seconds = val % 60;
    currTime.value = filteTime(hours) + ":" + filteTime(minutes) + ":" + filteTime(seconds);
    if (val <= 0) {
      clearInterval(interval.value);
      interval.value = null;
    }
    function filteTime (time: any) {
      if (time < 10) {
        return "0" + time;
      } else {
        return time;
      }
    }
  }, { immediate: true, deep: true });
  onMounted(() => {
    getListByDay();
  })
</script>

<style scoped lang="less">
  @import '@/assets/style/goodsList.less';
  .content {
    background-color: @light_background_color;
    color: #515a6e;
  }
  .seckill-title {
    margin: 20px auto;
    font-weight: bold;
    width: 200px;
    height: 40px;
    line-height: 40px;
    text-align: center;
    color: @text_color;
  }
  .time-line {
    width: 1200px;
    height: 60px;
    margin: 0 auto;
    background-color: #fff;
    display: flex;
    > div {
      padding: 0 30px;
      font-size: 16px;
      font-weight: bold;
      width: 240px;
      height: 100%;
      display: flex;
      align-items: center;
      &:hover {cursor: pointer;}
      .not-curr {
        height: 22px;
        line-height: 22px;
        border: 1px solid #999;
        border-radius: 20px;
        padding: 0 10px;
        margin-left: 10px;
        font-size: 12px;
        font-weight: normal;
      }
    }
    .currTimeline {
      background-color: @theme_color;
      color: #fff;
      >div:nth-child(1) {
        font-size: 20px;
      }
      >div:nth-child(2) {
        font-size: 14px;
        margin-left: 10px;
      }
    }
  }
  .goods-list {
    width: 1200px;
    margin: 20px auto;
    .goods-seckill-btn {
      position: absolute;
      right: 0;
      bottom: 0;
      width: 80px;
      color: #fff;
      height: 35px;
      text-align: center;
      line-height: 35px;
      font-size: 14px;
      background-color: @theme_color;
      margin-bottom: 1px;
      margin-right: 1px;
    }
    .goods-seckill-btn-gray {
      background-color: #666;
    }
    .goods-show-num1 {
      height: 14px;
    }
  }
</style>
